package com.fw.application.controller.open;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.annotation.PrintParam;
import com.fw.application.controller.base.BaseController;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.enums.PayTypeEnum;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.FwMoneys;
import com.fw.system.web.model.entity.FwShop;
import com.fw.system.web.model.entity.FwUser;
import com.fw.system.web.service.IFwLogsService;
import com.fw.system.web.service.IFwMoneysService;
import com.fw.system.web.service.IFwShopService;
import com.fw.system.web.service.IFwUserService;
import com.fw.utils.RandomUtils;
import com.fw.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.fw.mes.ResultUtils.success;

@RestController
@RequestMapping("/web/open")
@Api(tags = "开放接口")
public class OpenController implements BaseController {

    @Autowired
    private IFwShopService shopService;

    @Autowired
    private IFwUserService userService;
    @Autowired
    private IFwMoneysService moneysService;
    @Autowired
    private IFwLogsService logsService;

    @Value("${sjsp.version}")
    private String sjspVersion;

    @Autowired
    private SaticScheduleTask saticScheduleTask;

   /* @Autowired
    private AliComm aliComm;*/


    @GetMapping("/offlineShop")
    @ApiOperation("扫码线下支付 shopId【商铺编号】,money【消费金额】,keys【标识key】,payType【支付方式,0=支付宝,1=微信，2 = 银联】")
    @PrintParam
    public Result<String> offlineShop(@RequestParam("shopId") String shopId, @RequestParam("money") BigDecimal money, @RequestParam("keys") String keys, @RequestParam("payType") Integer payType) {
        // 接口鉴权
        FwUser user = getUser();
        FwShop fwShop = null;
        if (Objects.isNull(fwShop = shopService.getById(shopId))) {
            String newShopId = StrUtil.subBetween(keys, "shopId=shop_auth_per", "_fuwen_keys=shop_open_payshop_auth_per");
            Assert.isTrue(Objects.nonNull(fwShop = shopService.getById(newShopId)), "商铺编号错误,请核实!");
            shopId = newShopId;
        }
        List<Object> fieldValues = EnumUtil.getFieldValues(PayTypeEnum.class, "type");
        Assert.isTrue(fieldValues.contains(payType), "未匹配到支付方式,请核实!");
        Assert.isTrue(!StringUtils.equals(user.getId(), shopId), "违法操作,禁止刷单!");
        // Assert.isTrue(keys.equals("shopId=".concat(shopId).concat("_fuwen_keys=".concat(OpenAuthEnum.SHOP_AUTH_KEYS.getBody()).concat(shopId))),"商户开放失败,请核实!");
        //shopId=shop_auth_per1416956875844354048_fuwen_keys=shop_open_payshop_auth_per1416956875844354048
        //TODO 临时方案
        BigDecimal lineCustomer = fwShop.getLineCustomer();
        // 拿到让利比利润
        BigDecimal realAmount =  RandomUtils.mathNumber(lineCustomer,money);
        Assert.isTrue(RandomUtils.runodMath(money.subtract(realAmount)).compareTo(NumberUtil.add(0.10)) >= 0 ,"利润值过低,最低1毛钱起步!" );
        ;

        FwUser fwUser = userService.getOne(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId, fwShop.getUserId()));
        Assert.isTrue(org.apache.commons.lang3.StringUtils.isNoneBlank(fwUser.getAliPhone(), fwUser.getAliUserName()), "该商户未绑定支付宝!");
        String payBody = shopService.offlineShop(shopId, money, payType, user.getId());
        return success(payBody);
    }


    @GetMapping("/test")
    public void test() {
        // 代理级差逻辑 开启线程池
        userService.exe();
    }

   /* @GetMapping("/tr/{money}")
    public void tr(@PathVariable BigDecimal money) throws AlipayApiException {
        aliComm.aliTransfer("forcontinue@163.com",money);
    }*/


    //给后台暴露接口增加消证
    @PostMapping("/addXz")
    public boolean addXz(@RequestBody JSONObject object) {
        String userId = object.getStr("userId");
        BigDecimal disappear = object.getBigDecimal("disappear");
        FwMoneys fwMoneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        fwMoneys.setUpdateTime(LocalDateTime.now());
        boolean b = moneysService.updateById(fwMoneys.setDisappear(disappear.add(fwMoneys.getDisappear())));
        //增加日志
        logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(),"系统操作",disappear.toString());
        return b;

    }

    //给后台暴露接口增加消证
    @PostMapping("/subNum")
    public boolean subNum(@RequestBody JSONObject object) {
        String userId = object.getStr("userId");
        BigDecimal disappear = object.getBigDecimal("disappear");
        FwMoneys fwMoneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        fwMoneys.setUpdateTime(LocalDateTime.now());
        boolean b = moneysService.updateById(fwMoneys.setDisappear(fwMoneys.getDisappear().subtract(disappear)));
        logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(),"系统操作",disappear.toString());
        return b;
    }

    @GetMapping("/getVersion")
    @ApiOperation("版本统一核实处")
    public Result getVersion(){
        return success(sjspVersion);
    }

    @GetMapping("returnShangJiaById")
    public Result returnShangJiaById(){
        saticScheduleTask.returnShangJiaById();
        return success();
    }


    @GetMapping("releaseDisappearTasks")
    public Result releaseDisappearTasks(){
        saticScheduleTask.releaseDisappearTasks();
        return success();
    }
}
